package cn.edu.pzhu.javaweb.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * Application Lifecycle Listener implementation class LoginListener
 *
 */
@WebListener
public class LoginListener implements HttpSessionAttributeListener {
	private int count = 0;

    /**
     * Default constructor. 
     */
    public LoginListener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
     */
    public void attributeAdded(HttpSessionBindingEvent se)  { 
    	if ("username".equals(se.getName())) {
            ServletContext application = se.getSession().getServletContext();
           
            synchronized (LoginListener.class) {               
                Object obj = application.getAttribute("LOGIN");                
                if (obj==null) {
                    count=1;
                }else {
                	count = (Integer)obj + 1;
                }
                System.out.println("有用户登录了网站,username："+se.getValue());
                application.setAttribute("LOGIN", count);
            }
        }
    }

	/**
     * @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
     */
    public void attributeRemoved(HttpSessionBindingEvent se)  { 
    	if ("username".equals(se.getName())) {
            ServletContext application = se.getSession().getServletContext();
           
            synchronized (LoginListener.class) {               
                Object obj = application.getAttribute("LOGIN");                
                if (obj==null) {
                    count=0;
                }else {
                	count = (Integer)obj - 1;
                }
                System.out.println("有用户退出了网站,username："+se.getValue());
                application.setAttribute("LOGIN", count);
            }
        }
    }

	/**
     * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
     */
    public void attributeReplaced(HttpSessionBindingEvent se)  { 
         // TODO Auto-generated method stub
    }
	
}
